package com;


/**
 *
 * @author Vrishal
 */
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.Attribute;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import org.apache.log4j.Category;


public class ADAuth {

	   
    private String adServer = "ecwcorpad003";
    private String adPort = "389";
    private final String _domain = "CORP";
    private final String dn = "DC=corp,DC=ecw,DC=local";
    static String ATTRIBUTE_FOR_USER = "sAMAccountName";
    Category adlog;
    
    public ADAuth() {
       // adlog = EcwLogger.getLogger();
        try {
           // adlog.info("Getting logonserver info.");
            
            String sysenv = System.getenv("LOGONSERVER");
            if (sysenv != null && sysenv.startsWith("\\\\")) {
                adServer = sysenv.replace("\\\\", "");
            }
           // adlog.debug("AD Logon Server is: " + adServer);
        } catch (Exception e) {
           // adlog.error("Error in getting logonserver info: " + e.getMessage());
        	System.out.println("Error in getting logonserver info: ");
        }
    }
    
    public void setADServer(String adSvr, String adPort) {
        adServer = adSvr;
        this.adPort = adPort;
       // adlog.info("Successfully set AD LogonServer to " + adServer);
    }
    
    public String getADServer() {
        return adServer;
    }
    
    public boolean authUserAD(String username, String password) {
        boolean retVal = false;
        
        //adlog.debug("Now authenticating " + username + " in CORP.");
        String returnedAtts[] = {"sn", "givenName", "mail"};
        String searchFilter = "(&(objectClass=user)(" + ATTRIBUTE_FOR_USER + "=" + username + "))";
        //Create the search controls
        SearchControls searchCtls = new SearchControls();
        searchCtls.setReturningAttributes(returnedAtts);
        //Specify the search scope
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchBase = dn;
        Hashtable environment = new Hashtable();
        environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        //Using starndard Port, check your instalation
        environment.put(Context.PROVIDER_URL, "ldap://" + adServer + ":" + adPort);
        environment.put(Context.SECURITY_AUTHENTICATION, "simple");
        environment.put(Context.SECURITY_PRINCIPAL, username + "@" + _domain);
        environment.put(Context.SECURITY_CREDENTIALS, password);
        LdapContext ctxGC = null;
        //adlog.debug("Setting initial parameters for CORP authentication.");
        
        try {
            ctxGC = new InitialLdapContext(environment, null);
            // Search for objects in the GC using the filter
            NamingEnumeration answer = ctxGC.search(searchBase, searchFilter, searchCtls);
            while (answer.hasMoreElements()) {
                SearchResult sr = (SearchResult) answer.next();
                Attributes attrs = sr.getAttributes();
                if (attrs != null) {
                    //adlog.info("Authentication successful for user " + username);
                    retVal = true;
                    break;
                } else {
                   // adlog.info("Authentication failed for user " + username);
                	System.out.println("Authentication failed for user ");
                    retVal = false;
                }
            }
        } catch (NamingException e) {
            //adlog.error("NamingException error in authenticating user in AD: " + e.getMessage());
        	System.out.println("NamingException error in authenticating user in AD: ");
        } catch (Exception e) {
            //adlog.error("Error in authenticating user in AD: " + e.getMessage());
            System.out.println("Error in authenticating user in AD:");
        }
        return retVal;
    }
    
    public Attributes authenticateUser(String username, String password, String _domain, String host, String dn) {
        Attributes attrs;
        String returnedAtts[] = {"sn", "givenName", "mail"};
        String searchFilter = "(&(objectClass=user)(" + ATTRIBUTE_FOR_USER + "=" + username + "))";
        //Create the search controls
        SearchControls searchCtls = new SearchControls();
        //searchCtls.setReturningAttributes(returnedAtts);
        //Specify the search scope
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchBase = dn;
        Hashtable environment = new Hashtable();
        environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        //Using starndard Port, check your instalation
        environment.put(Context.PROVIDER_URL, "ldap://" + host + ":389");
        environment.put(Context.SECURITY_AUTHENTICATION, "simple");
        environment.put(Context.SECURITY_PRINCIPAL, username + "@" + _domain);
        environment.put(Context.SECURITY_CREDENTIALS, password);
        LdapContext ctxGC = null;
        try {
            ctxGC = new InitialLdapContext(environment, null);
            // Search for objects in the GC using the filter
            NamingEnumeration answer = ctxGC.search(searchBase, searchFilter, searchCtls);
            while (answer.hasMoreElements()) {
                SearchResult sr = (SearchResult) answer.next();
                attrs = sr.getAttributes();
                if (attrs != null) {
                    // return attrs;
                    String s = attrs.get("givenName").toString();
                    Attribute memberOf = attrs.get("memberOf");
                    if (memberOf != null) {// null if this user belongs to no group at all
                        for (int i = 0; i < memberOf.size(); i++) {
                            Attributes atts = ctxGC.getAttributes(memberOf.get(i).toString(), new String[]{"CN"});
                            Attribute att2 = atts.get("CN");
                            //adlog.debug("Group: " + att2.get().toString());
                        }
                    }
                    //adlog.debug("Given NAME: " + s);
                    return attrs;
                }
            }
        } catch (NamingException e) {
            //adlog.error("NamingException: " + e.getMessage());
            System.out.println("NamingException:");
        } catch (Exception e) {
            //adlog.error("General Exception: " + e.getMessage());
            System.out.println("General Exception:");
        }
        return null;
    }
    
   
}
